package cn.bobdeng.spc.mainserver.security;

import cn.bobdeng.smartlock.webcommons.BaseResult;
import cn.bobdeng.userrole.User;
import cn.bobdeng.userrole.UserServiceImpl;
import cn.bobdeng.userrole.exception.WrongPasswordException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
public class LoginController {

    @PostMapping("/login")
    public BaseResult login(HttpServletRequest request, @RequestBody LoginForm loginForm) {
        try {
            request.login(loginForm.getLoginName(), loginForm.getPassword());
            return BaseResult.getSuccess(null);
        } catch (ServletException e) {
            return BaseResult.getFail("用户名或密码错");
        }
    }

    @PostMapping("/logout")
    public BaseResult logout(HttpServletRequest request) {
        try {
            request.logout();
            return BaseResult.getSuccess(null);
        } catch (ServletException e) {
            e.printStackTrace();
            return BaseResult.getFail(e.getMessage());
        }
    }

    @GetMapping("/init_admin")
    public String initAdmin() {
        User admin = UserServiceImpl.initAdmin("admin", "123456");
        admin.setName("系统管理员");
        UserServiceImpl.saveProfile(admin);
        return "success";
    }

    @GetMapping("/get_login")
    public BaseResult getLogin(HttpServletRequest request) {
        try {
            UsernamePasswordAuthenticationToken userPrincipal = (UsernamePasswordAuthenticationToken) request.getUserPrincipal();
            MyUserDetails userDetails = (MyUserDetails) userPrincipal.getPrincipal();
            return BaseResult.getSuccess(new UserProfile(userDetails));
        } catch (Exception e) {
            return BaseResult.getFail("no login");
        }
    }

    @PutMapping("/change_password")
    public BaseResult changePassword(@RequestBody @Valid ChangePasswordForm changePasswordForm, HttpServletRequest request) {
        UsernamePasswordAuthenticationToken userPrincipal = (UsernamePasswordAuthenticationToken) request.getUserPrincipal();
        MyUserDetails userDetails = (MyUserDetails) userPrincipal.getPrincipal();
        return BaseResult.getSuccess(null);
    }

    @ExceptionHandler(WrongPasswordException.class)
    public BaseResult onWrongPass() {
        return BaseResult.getFail("密码错误");
    }

}
